/**
 * 工位管理-解除关联/删除(非空闲)
 */
import React, { useEffect, useState } from 'react';
import { Modal, Form, Select, Spin, message, Icon, Switch } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import cn from 'classnames';
import { handleUnRelativeEmployee, handleDeleteStation, getValidArea, handleUnRelativeEmployeeRelink, handleDeleteStationRelink, getAllSiteAddress } from '@/pages/AdminManage/service';
// import { getCompanyDetail } from '@/pages/Organization/OrgFlow/services';
import styles from '../index.less';


const FORM_DEFAULT_LAYOUT = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 17
    }
};
const MoreOperateModal = ({
    form,
    onOk,
    visible = false,
    info,
    type,
    ...rest
}) => {
    const { getFieldDecorator, validateFields, resetFields, getFieldValue, setFieldsValue } = form;
    const { employeeName, employeeCode, addressCode, id, organizationCode } = info;
    const [submitLoading, setSubmitLoading] = useState(false);
    const [areaLoading, setAreaLoading] = useState(false);
    const [areaData, setAreaData] = useState(null);
    const [areaList, setAreaList] = useState([]);
    const [subAreaList, setSubAreaList] = useState([]);
    const employeeLoading = false;
    const jobLoading = false;
    const isDelete = type === 'delete';
    const getArea = async addCode => {
        try {
            setAreaList([]);
            setSubAreaList([]);
            setAreaLoading(true);
            const { data: areaQueryData = {}, code, msg } = await getValidArea(addCode);
            if (code === 10000) {
                const keys = Object.keys(areaQueryData).sort();
                setAreaData(areaQueryData);
                setAreaList(keys);
            } else {
                message.error(msg)
            }
            setAreaLoading(false);
        } catch (e) {
            message.error(e);
            setAreaLoading(false);
        }
    };
    const handleOk = () => {
        validateFields(async(err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            if (values.switch && !areaList.length) {
                message.info('该办公地点无规划工位，请联系管理员');
                return;
            }
            setSubmitLoading(true);
            if (values.switch) {
                // 解除/删除并关联
                const params = {
                    unLinkId: id,
                    reLinkId: values.cubcileId,
                    employeeCode,
                    employeeName,
                    organizationCode
                };
                const { code, msg } = isDelete
                    ? await handleDeleteStationRelink(params)
                    : await handleUnRelativeEmployeeRelink(params);
                if (code === 10000) {
                    message.success(isDelete ? '删除工位且为员工分配其他工位成功！' : '解除关联且为员工分配其他工位成功！');
                    onOk();
                } else {
                    message.warning(msg);
                    switch (code) {
                        case 20007: // 工位已被删除
                            onOk();
                            break;
                        case 200017: // 重新分配的新工位已被删除
                            getArea(values.station);
                            break;
                        case 200018: // 工位已被解除关联
                            // 如果是删除，还需要额外咨询是否删除
                            if (isDelete) {
                              Modal.confirm({
                                  title: '确认删除该工位吗？',
                                  onOk: async() => {
                                      const { code: deleteCode, msg: deleteMsg } = await handleDeleteStation(id);
                                      if (deleteCode === 10000) {
                                          message.success('删除工位成功！');
                                          onOk();
                                      } else {
                                          message.error(deleteMsg);
                                      }
                                  }
                              });
                            } else {
                                // 如果是解除关联，直接关闭，刷新即可
                                onOk();
                            }
                            break;
                        case 20006: // 分配工位非空闲，请重新选择，重新分配的座位被占用
                            getArea(values.station);
                            break;
                        default:
                    }
                }
            } else {
                // 解除/删除
                const { code, msg } = isDelete
                    // 删除工位
                    ? await handleDeleteStation(id)
                    // 解除关联
                    : await handleUnRelativeEmployee({ id, cubicleLinkEmployee: { employeeCode } });
                if (code === 10000) {
                    message.success(isDelete ? '删除工位成功！' : '解除工位成功');
                } else {
                    message.error(msg);
                }
                onOk();
            }
            setSubmitLoading(false);
        });
    };
    // const { data: siteData = {}, loading, run } = useRequest(() => getCompanyDetail(info.companyCode), {
    const { data: siteList = [], loading, run } = useRequest(() => getAllSiteAddress({ auditStatuses: [1, 2, 3] }), {
        manual: true,
        ...defaultFormatResult
    });
    useEffect(() => {
        if (getFieldValue('switch')) {
            run();
        }
    }, [getFieldValue('switch')]);
    useEffect(() => {
        if (visible && isDelete) {
            getArea(addressCode);
        }
    }, [visible]);
    return (
        <Modal
            {...rest}
            visible={visible}
            width={600}
            onOk={handleOk}
            confirmLoading={submitLoading}
            destroyOnClose
            afterClose={() => {
                resetFields();
            }}
            className={styles.modalWrap}
        >
            <Spin spinning={employeeLoading || jobLoading}>
                <div className={styles.removeModalWrap}>
                    <div className={cn(styles.flex, styles.hintWrap)}>
                        <Icon type="exclamation-circle" theme="filled" style={{ color: 'rgba(38,38,38,0.25)', fontSize: 14 }}/>
                        <span>
                            {
                                isDelete ? '删除该工位后，该员工将处于无工位可用状态，请选择删除工位的后续操作！' : '解除关联后，该工位将重新释放为空闲状态，请选择后续操作！'
                            }
                        </span>
                    </div>
                    <div className={styles.flex}>
                        <span>为该员工分配其他工位</span>
                        {getFieldDecorator('switch', {
                            initialValue: isDelete,
                            valuePropName: 'checked'
                        })(
                            <Switch onChange={checked => {
                                if (checked) {
                                    getArea(addressCode);
                                }
                            }}/>
                        )}
                    </div>
                </div>
                {
                    getFieldValue('switch') ? <Form {...FORM_DEFAULT_LAYOUT} className={styles.employeeInfoForm}>
                        <Form.Item label="员工姓名" style={{ marginBottom: 0 }}>
                            <div>{employeeName}</div>
                        </Form.Item>
                        <Form.Item label="办公地点" style={{ marginBottom: 8 }}>
                            <Spin spinning={loading}>
                                {
                                    getFieldDecorator('station', {
                                        initialValue: addressCode
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            onChange={val => {
                                                setFieldsValue({
                                                    cubicleArea: undefined,
                                                    cubcileId: undefined
                                                });
                                                getArea(val);
                                            }}
                                            {...rest}
                                        >
                                            {siteList.map(item => (
                                                <Select.Option key={item.addressCode} value={item.addressCode}>
                                                    {item.addressName}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    )
                                }
                            </Spin>
                        </Form.Item>
                        <Form.Item label="工位编号" required style={{ marginBottom: 0 }}>
                            <Spin spinning={areaLoading}>
                                {
                                    areaList.length ?
                                        <>
                                            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}>
                                                {
                                                    getFieldDecorator('cubicleArea', {
                                                        initialValue: undefined,
                                                        rules: [
                                                            { required: true, message: '请选择区' }
                                                        ]
                                                    })(
                                                        <Select
                                                            placeholder="请选择区"
                                                            onChange={val => {
                                                                setFieldsValue({
                                                                    cubcileId: undefined
                                                                });
                                                                setSubAreaList(areaData[val]);
                                                            }}
                                                        >
                                                            {areaList.map(item => (
                                                                <Select.Option key={item} value={item}>
                                                                    {item}
                                                                </Select.Option>
                                                            ))}
                                                        </Select>
                                                    )
                                                }
                                            </Form.Item>
                                            <span style={{
                                                display: 'inline-block',
                                                width: '24px',
                                                textAlign: 'center'
                                            }}>-</span>
                                            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}>
                                                {
                                                    getFieldDecorator('cubcileId', {
                                                        initialValue: undefined,
                                                        rules: [
                                                            { required: true, message: '请选择编号' }
                                                        ]
                                                    })(
                                                        <Select
                                                            placeholder="请选择或输入"
                                                            showSearch
                                                        >
                                                            {subAreaList.map(item => (
                                                                <Select.Option key={item.id} value={item.id}>
                                                                    {item.cubicleCode}
                                                                </Select.Option>
                                                            ))}
                                                        </Select>
                                                    )
                                                }
                                            </Form.Item>
                                        </> : '该办公地点无规划工位，请联系管理员'
                                }
                            </Spin>
                        </Form.Item>
                    </Form> : null
                }
            </Spin>
        </Modal>
    );
};

export default Form.create()(MoreOperateModal);
